package com.mezz.bones.im.gateway.action.interfaces;


import com.alibaba.fastjson.JSONObject;
import com.mezz.bones.framework.core.strategy.IStrategy;
import com.mezz.bones.framework.base.util.ExecutionTimeLoggerUtil;
import com.mezz.bones.im.common.enums.ActionCodeEnum;
import com.mezz.bones.im.common.message.base.MessageHeader;
import com.mezz.bones.im.common.result.ImResultCode;
import com.mezz.bones.im.common.exception.ImBaseException;
import com.mezz.bones.im.common.message.base.Message;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public interface SysMessageAction<Req> extends IStrategy {

   Logger log = LoggerFactory.getLogger(SysMessageAction.class);

  /**
   * 执行相对应的业务
   *
   * @param
   * @param header
   * @param req   请求body
   *               ctx如果有响应输出 则统一用 ctx.channel输出
   *               下一个outHandler会把对象解析成相对应的 proto/text
   */
  void process(MessageHeader header, Req req, ChannelHandlerContext ctx);
  default void handler(Message msg, ChannelHandlerContext ctx) {

    log.debug("----------- MessageProcessor handler start:[{}]: msg: {}", this.tag(), JSONObject.toJSONString(msg));
    Req packData = null;
    try {
      packData = convert2T(msg.getBody());
    } catch (Exception e) {
      throw new ImBaseException(ImResultCode.SYS_ERROR,"消息请求body格式化异常");
    }

    ActionCodeEnum actionCodeEnum = ActionCodeEnum.findEnum(this.tag());

    Req finalPackData = packData;
    ExecutionTimeLoggerUtil.logExecutionTime(actionCodeEnum.getText(), () -> {

      //参数校验
      checkParam(finalPackData);

      //处理具体逻辑
      process(msg.getHeader(),finalPackData,ctx);
    });


    log.debug("----------- MessageProcessor handler end:[{}]", this.tag());

  }

  public void checkParam(Req finalPackData);

  Req convert2T(Object body);
}
